package test.mp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import test.mp.domain.dto.PageDTO;
import test.mp.domain.po.Address;
import test.mp.domain.po.User;
import test.mp.domain.query.UserQuery;
import test.mp.domain.vo.UserVO;
import test.mp.domain.vo.AddressVO;
import test.mp.enums.UserStatus;
import test.mp.mapper.UserMapper;
import test.mp.service.IUserService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName UserServiceImpl
 * @Description 用户服务实现类
 * @Author wxx
 * @Date 2024/08/13/23:53
 * @Version 1.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deductBalance(String id, Integer money) {
        // 1. 查询用户
        User user = getById(id);
        // 2.校验用户状态
        if(user == null || UserStatus.FORBIDDEN.equals(user.getStatus())){
            throw new RuntimeException("用户不存在或状态异常");
        }
        // 3.校验余额是否充足
        if(user.getBalance() < money){
            throw new RuntimeException("余额不足");
        }
        // 4.扣减余额 update t_user set balance = balance - 10 where id = 1
        //baseMapper.deductBalance(id, money);
        int remainBalance = user.getBalance() - money;
        lambdaUpdate().set(User::getBalance,remainBalance)
                .set(remainBalance == 0,User::getStatus,UserStatus.FORBIDDEN)
                .eq(User::getId,id)
                .eq(User::getBalance,user.getBalance()) //乐观锁
                .update();
    }

    @Override
    public List<User> queryUsers(UserQuery userQuery) {
        return lambdaQuery()
                .like(userQuery.getName() != null, User::getUsername,userQuery.getName())
                .eq(userQuery.getStatus() != null, User::getStatus, userQuery.getStatus())
                .ge(userQuery.getMinBalance() != null, User::getBalance, userQuery.getMinBalance())
                .le(userQuery.getMaxBalance() != null, User::getBalance, userQuery.getMaxBalance())
                .list();
    }

    @Override
    public UserVO queryUserAndAddressById(String id) {
        // 1. 查询用户
        User user = getById(id);
        if(user == null || UserStatus.FORBIDDEN.equals(user.getStatus())){
            throw new RuntimeException("用户状态异常");
        }
        // 2. 查询地址
        List<Address> addresses = Db.lambdaQuery(Address.class).eq(Address::getUserId, id).list();
        // 3. 封装VO
        // 3.1 转user的po为VO
        UserVO userVO = BeanUtil.copyProperties(user,UserVO.class);
        // 3.2 转address的po为VO
        if(CollUtil.isNotEmpty(addresses)){
            userVO.setAddresses(BeanUtil.copyToList(addresses, AddressVO.class));
        }
        return userVO;
    }

    @Override
    public List<UserVO> queryUserAndAddressByIds(List<String> ids) {
        // 1.查询用户
        List<User> users = listByIds(ids);
        if(CollUtil.isEmpty(users)){
            return Collections.emptyList();
        }
        // 2. 查询地址
        // 2.1 获取用户id集合
        List<String> userIds = users.stream().map(User::getId).collect(Collectors.toList());
        // 2.2 根据用户id查询地址
        List<Address> addressList = Db.lambdaQuery(Address.class).in(Address::getUserId, userIds).list();
        // 2.3 转换地址VO
        List<AddressVO> addressVOS = BeanUtil.copyToList(addressList, AddressVO.class);
        // 2.4 用户地址集合分组处理，相同用户的放入一个集合组中
        Map<String,List<AddressVO>> addressMap = new HashMap<>();
        if(CollUtil.isNotEmpty(addressList)){
            addressMap = addressVOS.stream().collect(Collectors.groupingBy(AddressVO::getUserId));
        }

        // 3. 封装VO
        List<UserVO> userList = new ArrayList<>(userIds.size());
        for(User user : users){
            // 3.1 转换User的PO为VO
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            userVO.setAddresses(addressMap.get(userVO.getId()));
            userList.add(userVO);
        }
        return userList;

    }

    @Override
    public PageDTO<UserVO> queryUsersPage(UserQuery userQuery) {
        String name = userQuery.getName();
        Integer status = userQuery.getStatus();
        // 1.构建分页条件
        Page<User> page = userQuery.toMapPageDefaultSortByUpdateTime();
        // 2. 分页查询
        Page<User> p = lambdaQuery()
                .like(name != null, User::getUsername, name)
                .eq(status != null, User::getStatus, status)
                .page(page);
        return PageDTO.of(p, user -> {
            // 拷贝基础属性
            UserVO userVO = BeanUtil.copyProperties(user, UserVO.class);
            // 2. 处理特殊逻辑
            userVO.setUsername(userVO.getUsername().substring(0, userVO.getUsername().length() - 2) + "**");
            return userVO;
        });
    }

}
